package com.example.wanbaqian.base;

import android.app.ActivityManager;
import android.app.AlarmManager;
import android.app.Application;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.support.multidex.MultiDex;
import android.util.Log;

import com.example.wanbaqian.config.CommonValue;
import com.ishumei.smantifraud.SmAntiFraud;
import com.lzy.okgo.OkGo;
import com.tencent.bugly.Bugly;
import com.tencent.bugly.beta.Beta;
import com.tencent.bugly.beta.interfaces.BetaPatchListener;
import com.umeng.socialize.PlatformConfig;
import com.umeng.socialize.UMShareAPI;
import com.zhy.autolayout.config.AutoLayoutConifg;

import java.util.Map;

import cat.ereza.customactivityoncrash.CustomActivityOnCrash;
import cn.jpush.android.api.JPushInterface;
import cn.tongdun.android.shell.FMAgent;
import cn.tongdun.android.shell.exception.FMException;

public class BaseApplication extends Application {

    private static BaseApplication singleton;
    public static Map<String, Long> map;
    private static final String TAG = "BaseApplication_log";
    public static Context context;
    private static int RequestTime=10*1000;
    public static String deviceId;

    public static BaseApplication getInstance() {
        if (singleton == null) {
            synchronized (BaseApplication.class) {
                if (singleton == null) {
                    singleton = new BaseApplication();
                }
            }
        }
        return singleton;
    }


    @Override
    public void onCreate() {
        super.onCreate();
        context = this;
        singleton = this;
        PlatformConfig.setWeixin("wxa8dc93a039c5c508", "68a802555d25c26f982e22033a24ff13");
//        PlatformConfig.setWeixin("wxbb32c8eb3d3b2913", "32d3519bf229d63b98c790c74d2f9aac");
        PlatformConfig.setQQZone("1106085697", "emVmj24MDac9Gp0h");
        UMShareAPI.get(this);
        CustomActivityOnCrash.install(this);
        AutoLayoutConifg.getInstance().useDeviceSize();
        setSminit();
        OkGo.init(this);
        OkGo.getInstance()
                .setConnectTimeout(RequestTime) //全局的连接超时时间
                .setReadTimeOut(RequestTime);  //全局的读取超时时间 默认60s
        //极光推送初始化
        JPushInterface.setDebugMode(true);
        JPushInterface.init(this);

        /*同盾初始化*/
        try {
            //  FMAgent.ENV_SANDBOX表示测试环境，FMAgent.ENV_PRODUCTION表示生产环境
            FMAgent.init(this, FMAgent.ENV_PRODUCTION);

        } catch (FMException e) {

            e.printStackTrace();

        }

        /*同盾初始化结束*/


        //设置调试设备
//        Bugly.setIsDevelopmentDevice(context, true);//13065ffa4e3f1f42f55
        Beta.betaPatchListener = new BetaPatchListener() {
            @Override
            public void onPatchReceived(String patchFile) {
            }

            @Override
            public void onDownloadReceived(long savedLength, long totalLength) {
            }

            @Override
            public void onDownloadSuccess(String msg) {
                //重启APP
                Intent mStartActivity = getBaseContext().getPackageManager().getLaunchIntentForPackage(getBaseContext().getPackageName());
                mStartActivity.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                PendingIntent mPendingIntent = PendingIntent.getActivity(context, 0x0001, mStartActivity, PendingIntent.FLAG_CANCEL_CURRENT);
                AlarmManager mgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                    mgr.setExact(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
                } else {
                    mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
                }
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        System.exit(0);
                    }
                }, 4000);
            }

            @Override
            public void onDownloadFailure(String msg) {
            }

            @Override
            public void onApplySuccess(String msg) {
            }

            @Override
            public void onApplyFailure(String msg) {
            }

            @Override
            public void onPatchRollback() {
            }
        };
//        Bugly.init(getApplicationContext(), "9e4bb55f43", false);
    }

    /**
     * 数美配置***
     */
    private void setSminit(){
        // 如果 AndroidManifest.xml 中没有指定主进程名字，主进程名默认与 packagename 相同
        if(getCurProcessName(this).equals(this.getPackageName())){
            SmAntiFraud.SmOption option=new SmAntiFraud.SmOption();
            option.setOrganization(CommonValue.ORGANIZATION); // organization 代码 不要传 AccessKey
            option.setChannel(CommonValue.APPSTORE);//渠道代码

            // 可选的方式，deviceId 拉取成功的事件监听，异步方式
            SmAntiFraud.registerServerIdCallback(
                    new SmAntiFraud.IServerSmidCallback() {
                        @Override
                        public void onReceive(String serverId, int code) {
                            Log.i(TAG, "onReceive:-- "+serverId);
                        }
                    });
            SmAntiFraud.create(this, option);
            // 获取 deviceId，这个接口在真正的注册或登录事件产生的地方调用。
            // create 后马上调用返回的是本地的 deviceId，
            // 本地 deviceId 和服务器同步需要一点时间。
            deviceId = SmAntiFraud.getDeviceId();
        }
    }

    /**
     * 取得当前进程名
     * @param context
     * @return
     */
    public String getCurProcessName(Context context) {
        int pid = android.os.Process.myPid();
        ActivityManager mActivityManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningAppProcessInfo appProcess : mActivityManager
                .getRunningAppProcesses()) {
            if (appProcess.pid == pid) {
                return appProcess.processName;
            }
        }
        return null;
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        // you must install multiDex whatever tinker is installed!
        MultiDex.install(base);
        Beta.installTinker();
    }

}
